from .base_handler import BaseRequestHandler
from ..utility import db_data_tool, data_tool
import json


class SUTPageElementManageHandler(BaseRequestHandler):
    """被测系统页面 元素 管理"""
    async def get_default(self):
        """查询 指定类型、指定系统、指定页面 的元素信息"""
        system_id = self.get_argument('system_id', None)
        element_type = self.get_argument('type', None)
        page_id = self.get_argument('node_id', None)
        if element_type:  # 查询 指定页面/系统的 元素信息
            if page_id and system_id:
                data = await self.mdb.query('''
                  select e.*, tuser.real_name as creator_name, tuser1.real_name as last_mender_name
                  , tuser.real_name as creator_name 
                  from test_element e
                    left join tdp_user tuser on e.creator_id=tuser.id
                    left join tdp_user tuser1 on e.last_mender_id=tuser1.id
                  , test_element_node pg, test_element_node sys 
                  where sys.id=%s and pg.id=%s and pg.parent_node_id=sys.id and e.page_id=pg.id
                  ''', system_id, page_id)
            elif page_id:
                data = await self.mdb.query(
                    '''select tuser.real_name as creator_name, e.* from  test_element e
                          left join tdp_user tuser on e.creator_id=tuser.id
                        where e.page_id=%s and e.type=%s'''
                    , page_id, element_type
                )
            elif system_id:
                data = await self.mdb.query('''
                  select e.*, creator.real_name as creator_name from test_element e
                    left join tdp_user creator on e.creator_id=creator.id
                  , test_element_node pg, test_element_node sys 
                  where sys.id=%s and e.type=%s and pg.parent_node_id=sys.id and e.page_id=pg.id
                  ''', system_id, element_type)
            else:
                data = await self.mdb.query(
                    '''
                    select e.*, creator.real_name as creator_name from test_element e
                      left join tdp_user creator on e.creator_id=creator.id
                     where `type`=%s
                    ''', element_type
                )
        elif system_id:
            data = await self.mdb.query(
                '''
                  select e.*, IFNULL(frame.element_name, '') as frame_name, tuser.real_name as creator_name
                  , tuser1.real_name as last_mender_name 
                  from test_element e
                    left join test_element_node page on page.id = e.page_id
                    left join test_element_node tsystem on tsystem.id = page.parent_node_id
                    left join test_element frame on frame.id = e.frame_id
                    left join tdp_user tuser on e.creator_id=tuser.id
                    left join tdp_user tuser1 on e.last_mender_id=tuser1.id
                  where tsystem.id = %s
                  '''
                , system_id)
        elif page_id:
            data = await self.mdb.query('''
              select e.*, IFNULL(frame.element_name, '') as frame_name, tuser.real_name as creator_name
              , tuser1.real_name as last_mender_name 
              from test_element e 
                left join test_element frame on frame.id=e.frame_id
                left join tdp_user tuser on e.creator_id=tuser.id
                left join tdp_user tuser1 on e.last_mender_id=tuser1.id
              where e.page_id=%s
              ''', page_id)
        else:
            data = await self.mdb.query(
                '''
                select e.*, IFNULL(frame.element_name, '') as frame_name, tuser.real_name as creator_name
                , tuser1.real_name as last_mender_name 
                from test_element e 
                  left join test_element frame on frame.id=e.frame_id
                  left join tdp_user tuser on e.creator_id=tuser.id
                  left join tdp_user tuser1 on e.last_mender_id=tuser1.id
                '''
            )
        self.success_data = data

    async def get_params(self):
        """查询 元素参数"""
        element_id = self.get_argument('element_id')
        self.success_data = await self.get_element_params([element_id])

    @classmethod
    async def get_element_params(cls, element_id_list: list) -> list:
        param_list = []
        frames_info = await cls.mdb.query("select id, frame_id, params from test_element where type='web_frame'")
        s = db_data_tool.data2sql_in(element_id_list)
        if not s or s == '()':
            return []
        elements_info = await cls.mdb.query("select frame_id, params from test_element where id in{s}".format(s=s))
        element_frames = db_data_tool.get_dlist_key_values(elements_info, key='frame_id', where_not={'frame_id': ''})
        frames = element_frames.copy()
        for frame_id in element_frames:
            frames += db_data_tool.get_tree_parent_nodes_by_dlist(
                nodes_dlist=frames_info,
                dlist_prase_key='id',
                parent_name='frame_id',
                child_id=int(frame_id)
            )
        for frame_id in frames:
            params = db_data_tool.get_dlist_key_values(dlist=frames_info, key='params', where={'id': frame_id})
            for param in params:
                param_list += json.loads(param)
        for element in elements_info:
            param_list += json.loads(element['params'])

        param_list = set(param_list)
        param_list = list(param_list)

        return param_list

    async def get_sutFrames(self):
        data = await self.mdb.query('''
          select * from test_element e, test_element_node ten 
        ''')
        self.success_data = data

    async def post_elementInfo(self):
        element_id = self.get_argument('id')
        data = await self.mdb.query(
            '''
              select e.*, frame.element_name as frame_name
              from test_element e 
                left join test_element frame
                  on frame.id = e.frame_id
              where e.id = %s
              '''
            , element_id
        )
        self.success_data = data

    async def post_frames(self):
        """获取指定系统中的frame类型元素"""
        system_id = self.get_argument('system_id')
        data = await self.mdb.query(
            '''
              select *
              from test_element e
                left join test_element_node page
                  on page.id = e.page_id
                left join test_element_node tsystem
                  on tsystem.id = page.parent_node_id
              where tsystem.id = %s and e.type = 2
              '''
            , system_id)
        self.success_data = data

    async def post_edit(self):
        """新增、编辑元素信息"""
        element_id = self.get_argument('id', None)
        frame_id = self.get_argument('frame_id', None)
        by_value = self.get_argument('by_value', '')
        d = {
            'element_name': self.get_escaped_argument('element_name'),
            'page_id': self.get_argument('page_id'),
            'location_by_id': self.get_argument('location_by_id'),
            'by_value': by_value,
            'frame_id': db_data_tool.str2db_null(frame_id),
            'type': self.get_argument('type', None),
            'mark': self.get_argument('mark')
        }

        # -------- 获取测试元素中的参数 --------
        if by_value:
            try:
                params = data_tool.get_str_format_keys(by_value)
            except Exception as e:
                self.exception_msg = "参数使用错误，请注意便用'{{}}'代替'{}'！"
                self.app_logger.exception(e)
                raise
            d['params'] = params
        if not element_id:
            d['creator_id'] = self.current_user_id
            await self.mdb.insert_by_dict(table='test_element', data=d)
        else:
            d['last_mender_id'] = self.current_user_id
            await self.mdb.update_by_dict(table='test_element', colv=d, where={'id': element_id})

    async def post_del(self):
        element_id = self.get_argument('id')
        await self.mdb.delete_by_dict(table='test_element', where={'id': element_id})

